import React, { useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { Upload, Image as ImageIcon } from 'lucide-react';
import { useDispatch } from 'react-redux';
import { setCurrentImage, setOriginalImage } from '../store/slices/imageSlice';

interface ImageUploadProps {
  onImageLoad?: (imageData: string) => void;
}

const ImageUpload: React.FC<ImageUploadProps> = ({ onImageLoad }) => {
  const dispatch = useDispatch();

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      const file = acceptedFiles[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const imageData = e.target?.result as string;
          dispatch(setOriginalImage(imageData));
          dispatch(setCurrentImage(imageData));
          onImageLoad?.(imageData);
        };
        reader.readAsDataURL(file);
      }
    },
    [dispatch, onImageLoad]
  );

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'],
    },
    multiple: false,
  });

  return (
    <div
      {...getRootProps()}
      className={`
        border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors
        ${isDragActive
          ? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20'
          : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
        }
      `}
    >
      <input {...getInputProps()} />
      <div className="flex flex-col items-center space-y-4">
        {isDragActive ? (
          <ImageIcon className="w-12 h-12 text-blue-500" />
        ) : (
          <Upload className="w-12 h-12 text-gray-400" />
        )}
        <div>
          <p className="text-lg font-medium text-gray-700 dark:text-gray-300">
            {isDragActive ? '放下图片文件' : '拖拽图片到这里'}
          </p>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            或点击选择文件 (支持 PNG, JPG, GIF, WebP)
          </p>
        </div>
      </div>
    </div>
  );
};

export default ImageUpload;